package com.banciyuan.bcywebview.biz.pc;

import android.content.Context;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.myinterface.PushActionInterface;
import com.banciyuan.bcywebview.biz.write.write.WriteActivity;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.NetUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PersonHelper {

    private static final String HEAD_FORMAT = "%s/%s.jpg";
    public static final String FAT = "fat";
    public static final String BIG = "big";
    public static final String MIDDLE = "middle";
    public static final String SMALL = "small";

    public static final float FAT_SIZE = 500f;
    public static final float BIG_SIZE = 150f;
    public static final float MIDDLE_SIZE = 50f;
    public static final float SMALL_SIZE = 30f;

    private Context mContext;
    private PushActionInterface mInterface;
    private RequestQueue mQueue;

    private String mToken = "";
    private String mPrefix = "";
    private String mPath = "";

    private Boolean Writeflag = false;

    public Boolean cancelRequset = false;

    private int successNum = 0;

    public PersonHelper(Context mContext, PushActionInterface mInterface) {
        this.mContext = mContext;
        this.mInterface = mInterface;
        mQueue = VolleyQueue.getRquest(mContext);
    }

    private String getFilename(String type) {
        mPath = String.format(HEAD_FORMAT, mPrefix, type);
        return mPath;
    }

    public void doPush() {
        cancelRequset = false;
        if (!ifNetWork()) {
            mInterface.onNetError("");
            return;
        }

        if (Writeflag) return;
        Writeflag = true;
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                doUpFile(response);
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mInterface.onNetError("");
            }
        };

        String url = "";
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(mContext).getToken()));
        url = HttpUtils.BASE_URL + UserApi.getGetuploader();
        Map<String, String> map = HttpUtils.getData(paramsList);

        StringRequestParam getUserdataRequest = new StringRequestParam(Method.POST, url, map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
    }

    public void doUpFile(String result) {
        if (!ifNetWork()) {
            mInterface.onNetError("");
            return;
        }

        try {
            JSONObject jsonResult = new JSONObject(result).getJSONObject("data");
            mToken = jsonResult.getString("cloud_upToken");
            mPrefix = jsonResult.getString("cloud_prefix");
            doPicIO(FAT);
            doPicIO(BIG);
            doPicIO(MIDDLE);
            doPicIO(SMALL);
        } catch (JSONException e) {
            mInterface.onNetError("");
        }
    }


    private void doPicIO(String type) {
        if (!ifNetWork()) {
            mInterface.onNetError("");
            return;
        }
        UploadManager uploadManager = new UploadManager();
        uploadManager.put(new File(ImageManager.getTemp(mContext) + type), getFilename(type), mToken, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                successNum++;
                if (successNum >= 4) doPushDaily();
                else return;
            }
        }, null);
    }


    private void doPushDaily() {
        if (!ifNetWork()) {
            mInterface.onNetError("");
            return;
        }
        successNum = 0;
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Writeflag = false;
                mInterface.PushSuccess("http://user.bcyimg.com/" + getFilename(BIG));
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Writeflag = false;
                mInterface.onNetError("");
            }
        };

        List<BcyPair> paramsList = new ArrayList<>();
        String url = "";
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(mContext).getToken()));
        url = HttpUtils.BASE_URL + UserApi.getAddavatar();
        Map<String, String> map = HttpUtils.getData(paramsList);

        StringRequestParam getUserdataRequest = new StringRequestParam(Method.POST, url, map, onSuccess, onError);
        mQueue.add(getUserdataRequest);
    }

    public Boolean ifNetWork() {
        if (!NetUtils.checkNetwork(mContext)) {
            mInterface.onNetError("");
            return false;
        }
        if (cancelRequset) {
            mInterface.onNetError("");
            return false;
        }
        return true;
    }

    public void cancelAll() {
        Writeflag = false;
        cancelRequset = true;
        mQueue.cancelAll(WriteActivity.WRITE_ACTIVITY);
    }
}